package com.sunshine.controller;

import com.sunshine.bean.Article;
import com.sunshine.model.ArticleMapper;
import com.sunshine.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static com.sunshine.util.Result.json;

/**
 * Created by along on 11/18/17.
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleMapper articleMapper;

    @GetMapping
    public Map<String, Object> read(@RequestParam(value = "id") int id) {
        Article article = articleMapper.findById(id);
        if (article == null) {
            return json(Result.STATUS_CODE.SYSTEM_ERRO);
        } else {
            articleMapper.read(id);
            return json(Result.STATUS_CODE.SUCCESS, article);
        }
    }

    @GetMapping("/hotQuestion")
    public Map<String, Object> hotQuestion() {
        List<Article> articleList = articleMapper.findByType(Article.TYPE.HOTQUESTION.toString());
        return putList(articleList);
    }

    @GetMapping("/hotQuestion/preview")
    public Map<String, Object> hotQuestionReview() {
        List<Article> articleList = articleMapper.previewByType(Article.TYPE.HOTQUESTION.toString(),10);
        return putList(articleList);
    }

    @GetMapping("/moment")
    public Map<String, Object> moment() {
        List<Article> articleList = articleMapper.findByType(Article.TYPE.MOMENT.toString());
        return putList(articleList);
    }

    @GetMapping("/moment/preview")
    public Map<String, Object> momentReview() {
        List<Article> articleList = articleMapper.previewByType(Article.TYPE.MOMENT.toString(),10);
        return putList(articleList);
    }

    private Map<String, Object> putList(List<Article> articleList) {
        if (articleList == null) {
            return json(Result.STATUS_CODE.SYSTEM_ERRO);
        } else {
            List<Map<String, Object>> resultList = new LinkedList<>();
            for (Article article : articleList) {
                Map<String, Object> item = new HashMap<>();
                item.put("title", article.getTitle());
                item.put("id", article.getId());
                resultList.add(item);
            }
            return json(Result.STATUS_CODE.SUCCESS, resultList);
        }
    }
}
